<template>

  <div class="app-container">
    <!-- 加载中 -->
    <div v-show="visible" class="loading-overlay">
    <div class="loading-content">
      <el-loading-spinner size="large"></el-loading-spinner>
      <p class="loading-text">{{ text.default }}</p>
    </div>
  </div>
    <el-tag
  class="file-tag"
>
  流程引擎审核
</el-tag>
    <!-- 数据表格 -->
    <el-table :data="auditList" border style="width: 100%">
      <el-table-column prop="name" label="姓名" width="80"></el-table-column>
      <el-table-column prop="studentId" label="学号" width="120"></el-table-column>
      <el-table-column prop="groupNum" label="分组编号" width="100"></el-table-column>
      <el-table-column prop="workload" label="给予工作量" width="100"></el-table-column>
      <el-table-column prop="remark" label="审核意见"></el-table-column>
<el-table-column prop="canAnnotate" label="是否成功">
  <template slot-scope="{ row }">
    <div v-if="row.canAnnotate === '1'">成功</div>
    <div v-if="row.canAnnotate === '0'">失败
     <div>原因：{{row.cause}}</div>
    </div>
  </template>

</el-table-column>
<el-table-column prop="title" label="文件标题" width="100"></el-table-column>
      <!-- 文件展示列 -->
      <el-table-column prop="workFile" label="相关文件">
        <template slot-scope="{ row }">
          <div v-for="(file, index) in formatFiles(row.workFile)" :key="index">
            <el-tag
              class="file-tag"
              @click.native="handlePreview(file)"
            >
              {{ getFileName(file) }}
              <i :class="getFileIcon(file)" style="margin-left: 5px;"></i>
            </el-tag>
          </div>
        </template>
      </el-table-column>

      <!-- 状态列 -->
      <el-table-column prop="status" label="状态" width="120">
        <template slot-scope="{ row }">
          <el-tag :type="statusType[row.status]">
            {{ statusMap[row.status] || '未知状态' }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="240">
        <template slot-scope="{ row }">
          <el-button

            type="primary"
            size="small"
            @click="showAuditDialog(row, '3')"
          >
            审核通过
          </el-button>
          <el-button

            type="danger"
            size="small"
            @click="showAuditDialog(row, '4')"
          >
            审核不通过
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 审核对话框 -->
    <el-dialog :visible.sync="auditDialogVisible" title="审核处理">
      <el-form
        :model="auditForm"

        ref="auditFormRef"
        label-width="80px"
      >
        <el-form-item label="处理状态" prop="status">
          <el-radio-group v-model="auditForm.status">
            <el-radio label="3">通过</el-radio>
            <el-radio label="4">不通过</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="工作量" prop="workload" v-if="auditForm.status === '3'">
          <el-input
            v-model.number="auditForm.workload"
            type="number"
            placeholder="请输入通过的工作量"
          ></el-input>
        </el-form-item>

        <el-form-item label="审核意见" prop="remark">
          <el-input
            v-model="auditForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入审核意见（可填写建议或驳回原因）"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="auditLoading"
          @click="submitAudit"
        >
          确认审核
        </el-button>
      </div>
    </el-dialog>

    <!-- 文件预览对话框 -->
    <el-dialog :visible.sync="previewDialogVisible" width="80%">
      <div v-if="previewType === 'image'">
        <el-image
          :src="previewUrl"
          :preview-src-list="[previewUrl]"
          fit="contain"
        ></el-image>
      </div>
      <div v-else-if="previewType === 'ofihaseoidfji'" class="pdf-preview">
        <iframe
          :src="`https://docs.google.com/viewer?url=${encodeURIComponent(previewUrl)}&embedded=true`"
          width="100%"
          height="600"
        ></iframe>
      </div>
      <div v-else class="other-file">
        <el-button type="primary" @click="downloadFile(previewUrl)">
          下载文件
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProject, getProject, delProject, addProject, updateProject,checkProject,checkProjectByEngine } from "@/api/remark/project";
import request from '@/utils/request';
export default {
  data() {
    return {
       visible: {
      type: Boolean,
      default: false
    },
    // 加载文本提示
    text: {
      type: String,
      default: '加载中...'
    },
      statusMap: {
        '0': '待审核',
        '2': '团长审核通过',
        '4': '已驳回'
      },
      statusType: {
        '0': 'warning',
        '2': 'success',
        '4': 'danger'
      },
      auditList: [],
      baseFileUrl: process.env.VUE_APP_BASE_API,
      previewDialogVisible: false,
      previewUrl: '',
      previewType: '',
      auditDialogVisible: false,
      auditForm: {
        status: '',
        workload: null,
        remark: ''
      },
      auditRules: {
        status: [{ required: true, message: '请选择处理状态', trigger: 'change' }],
        workload: [{ required: true, message: '通过时必须填写工作量', trigger: 'blur' }, { type: 'number', min: 0, message: '工作量必须为非负整数', trigger: 'blur' }],
        remark: [{ required: true, message: '请填写审核意见', trigger: 'blur' }]
      },
      currentRow: null,
      auditLoading: false
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    // 显示审核对话框
    showAuditDialog(row, defaultStatus) {
      console.log(row)
      this.currentRow = row
      this.auditForm = {
        status: defaultStatus,
        workload: defaultStatus === '3' ? row.workload : null,
        remark: row.remark || ''
      }
      this.auditDialogVisible = true
    },

    // 提交审核
    async submitAudit() {

      if (!this.$refs.auditFormRef.validate()) return

      try {
        this.auditLoading = true
        await checkProjectByEngine({
          submitId: this.currentRow.submitId,
          status: this.auditForm.status,
          // status: '0',
          workload: this.auditForm.status === '3' ? this.auditForm.workload : null,
          remark: this.auditForm.remark,
          userId:this.currentRow.userId
        },this.currentRow.taskId)

        // 更新表格数据
        const index = this.auditList.findIndex(item => item.submitId === this.currentRow.submitId)
        this.auditList[index] = {
          ...this.auditList[index],
          status: this.auditForm.status,
          workload: this.auditForm.workload,
          remark: this.auditForm.remark
        }
        this.$message.success('审核操作成功')
        this.auditList=[]
        await this.loadData()
        this.auditDialogVisible = false
      } finally {
        this.auditLoading = false
      }
    },

    // 文件处理方法保持不变
    formatFiles(files) {
      return files.split(',').map(file => `${this.baseFileUrl}${file}`)
    },
    getFileName(url) {
      return url.split('/').pop()
    },
    getFileIcon(url) {
      const ext = url.split('.').pop().toLowerCase()
      if (['png','jpg','jpeg','gif'].includes(ext)) return 'el-icon-picture'
      if (ext === 'pdf') return 'el-icon-document'
      return 'el-icon-folder'
    },
    handlePreview(url) {
      const ext = url.split('.').pop().toLowerCase()
      this.previewUrl = url
      this.previewType = ['png','jpg','jpeg','gif'].includes(ext) ? 'image'
        : ext === 'pdf' ? 'pdf'
        : 'other'
      this.previewDialogVisible = true
    },
    downloadFile(url) {
      const link = document.createElement('a')
      link.href = url
      link.download = this.getFileName(url)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },

    // 加载数据
    async loadData() {
       this.visible=true
  try {
    // 获取流程引擎列表
    const taskResponse = await request({
      url: '/task/list',
      method: 'get',
      params: {
        pageNum: 1,
        pageSize: 1000
      }
    });

if(taskResponse==null){
      return
    }
    // 提取 remarkId 数组
    const taskIds = taskResponse.map(item => item.remarkId);
    console.log('taskIds:', taskIds);

    // 构建 URL 参数（将数组转换为逗号分隔的字符串）
    const urlParams = taskIds.join(',');

    // 获取项目数据
    const projectResponse = await request({
      url: `/remark/project/batch/${urlParams}`,
      method: 'get',
      params: {
        pageNum: 1,
        pageSize: 1000,
        status: 0
      }
    });

    // 合并两个响应的数据
    this.auditList = projectResponse.data.map(item => {
      const taskItem = taskResponse.find(t => t.remarkId === item.submitId);
      return {
        ...item,
        taskId: taskItem?.id || null // 添加 taskId 字段
      };
    });
 this.visible=false
    console.log('合并后的 auditList:', this.auditList);
  } catch (error) {
     this.visible=false

    console.error('加载数据失败:', error);
    // 处理错误
  }finally{
    this.visible=false
  }
}
  }
}
</script>

<style scoped>
/* 样式保持不变 */
.file-tag {
  margin: 2px;
  cursor: pointer;
  transition: all 0.3s;
}

.file-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}

.pdf-preview {
  width: 100%;
  height: 600px;
}

.other-file {
  text-align: center;
  padding: 20px;
}
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-content {
  text-align: center;
}

.loading-text {
  margin-top: 15px;
  color: #606266;
  font-size: 16px;
}
</style>
